<template>
  <el-upload
    class="image-uploader"
    :key="imagecropperKey"
    :show-file-list="false"
    accept="image/*"
    :headers="headers"
    :action="uploadUrl"
    :before-upload="beforeAvatarUpload"
    :on-success="cropSuccess"
  >
    <img v-if="image" :src="image" class="image" />
    <i v-else class="el-icon-plus image-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "ImageUpload",
  props: {
    //图片虚拟路径
    value: {
      type: String,
      default: "",
    },
  },
  watch: {
    //监听value变化
    value(val) {
      if (
        val === undefined ||
        val === "undefined" ||
        val === null ||
        val === "null" ||
        val === ""
      ) {
        this.image = "";
      } else {
        // 外部内容发生变化时，刷新图片(转码)
        this.image = encodeURI(
          this.root + "adminApi/Utility/PreviewPic?VirtualPath=" + val
        );
      }
    },
  },
  computed: {
    ...mapGetters(["root","token"]),
    // 配置图片上传地址
    uploadUrl(){
      return this.root + `adminApi/Utility/UploadPic`
    },
    //请求Headers
    headers(){
      return {
        Authorization : "Bearer " + this.token
      }
    },
  },
  data() {
    return {
      //图像上传
      imagecropperKey: 0,
      image: "",
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },
    //上传成功回调
    cropSuccess(jsonData, field) {
      this.imagecropperKey = this.imagecropperKey + 1;
      //成功回调父组件方法
      this.$emit("input", jsonData.data);
      //刷新图片(转码)
      this.image = encodeURI(
        this.root +
          `adminApi/Utility/PreviewPic?VirtualPath=` +
          jsonData.data
      );
      this.$message({
        message: "保存成功",
        type: "success",
      });
    },
  },
};
</script>

<style>
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.image-uploader .el-upload:hover {
  border-color: #409eff;
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>